package com.zx.zxpicture.infrstructure.manager;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.zx.zxpicture.infrstructure.common.ErrorCode;
import com.zx.zxpicture.infrstructure.config.CosClientConfig;
import com.zx.zxpicture.infrstructure.exception.BusinessException;
import com.zx.zxpicture.infrstructure.exception.ThrowUtils;
import com.zx.zxpicture.interfaces.dto.picture.UploadPictureResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 文件服务
 * @deprecated 已废弃，改为使用 upload 包的模板方法优化
 */
@Service
@Slf4j
@Deprecated
public class FileManager {
    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private CosManager cosManager;
    @Resource
    private COSClient cosClient;

    /**
     * 文件上传
     * @param multipartFile
     * @param uploadPathPrefix
     * @return
     */
    public UploadPictureResult fileUploadPicture(MultipartFile multipartFile, String uploadPathPrefix) {
        validPicture(multipartFile);
        //获取文件名
        String originFilename = multipartFile.getOriginalFilename();
        String uuid = RandomStringUtils.randomAlphanumeric(10);
        //文件路径
        String uploadName = String.format("%s_%s.%s", DateUtil.formatDate(new Date()), uuid,
                FileUtil.getSuffix(originFilename));
        String uploadPath = String.format("/%s/%s", uploadPathPrefix, uploadName);
        //创建临时文件
        File file = null;
        try {
            file = getFile(multipartFile, uploadPath);
            //上传文件到cos
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, file);
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            // 封装返回结果
            UploadPictureResult uploadPictureResult = new UploadPictureResult();
            int picWidth = imageInfo.getWidth();
            int picHeight = imageInfo.getHeight();
            double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
            uploadPictureResult.setPicName(FileUtil.mainName(originFilename));
            uploadPictureResult.setPicWidth(picWidth);
            uploadPictureResult.setPicHeight(picHeight);
            uploadPictureResult.setPicScale(picScale);
            uploadPictureResult.setPicFormat(imageInfo.getFormat());
            uploadPictureResult.setPicSize(FileUtil.size(file));
            uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + uploadPath);
            return uploadPictureResult;
        } catch (IOException e) {
            log.error("图片上传到对象存储失败", e);
            throw new RuntimeException("文件上传到COS失败");
        } finally {
            //删除文件
            this.deleteTempFile(file);
        }
    }

    public UploadPictureResult urlUploadPicture(String fileUrl, String uploadPathPrefix){
        //todo 校验图片是否合法
        validPicture(fileUrl);
        //todo 获取文件名
        String originFilename = FileUtil.mainName(fileUrl);
        String uuid = RandomStringUtils.randomAlphanumeric(10);
        //文件路径
        String uploadName = String.format("%s_%s.%s", DateUtil.formatDate(new Date()), uuid,
                FileUtil.getSuffix(originFilename));
        String uploadPath = String.format("/%s/%s", uploadPathPrefix, uploadName);

        //todo 创建临时文件
        File file = null;
        try {
            //创建临时文件
            file = File.createTempFile(uploadPath, null);
            //下载图片到临时文件
            HttpUtil.downloadFile(fileUrl, file);
            //上传文件到cos
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, file);
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            // todo 封装返回结果
            UploadPictureResult uploadPictureResult = new UploadPictureResult();
            int picWidth = imageInfo.getWidth();
            int picHeight = imageInfo.getHeight();
            double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
            uploadPictureResult.setPicName(FileUtil.mainName(originFilename));
            uploadPictureResult.setPicWidth(picWidth);
            uploadPictureResult.setPicHeight(picHeight);
            uploadPictureResult.setPicScale(picScale);
            uploadPictureResult.setPicFormat(imageInfo.getFormat());
            uploadPictureResult.setPicSize(FileUtil.size(file));
            uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + uploadPath);
            return uploadPictureResult;
        } catch (IOException e) {
            log.error("图片上传到对象存储失败", e);
            throw new RuntimeException("文件上传到COS失败");
        } finally {
            //删除文件
            this.deleteTempFile(file);
        }

    }

    /**
     * 校验文件(url上传)
     * @param fileUrl
     */
    private void validPicture(String fileUrl){
        ThrowUtils.throwIf(fileUrl == null, ErrorCode.PARAMS_ERROR, "路径不能为空");
        //1.校验url格式
        try {
            new URL(fileUrl);
        } catch (MalformedURLException e) {
            log.error("图片url格式不满足要求",e);
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"图片url格式不满足要求");
        }
        //2.校验url协议
        if(!fileUrl.startsWith("http:") && !fileUrl.startsWith("https:")){
            log.error("图片url只支持http或https协议：{}",fileUrl);
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"图片url只支持http或https协议");
        }

        //3.发送HEAD请求查看图片是否存在
        HttpResponse response = null;
        try{
            response = HttpUtil.createRequest(Method.HEAD, fileUrl).execute();
            if (response.getStatus() != HttpStatus.HTTP_OK) {
                //图片不存在，直接返回，不需其他判断
                //因为有些图片网站不支持HEAD请求获取图片信息
                return;
            }
            // 4. 校验文件类型
            //拿到文件的类型
            String contentType = response.header("Content-Type");
            if (StrUtil.isNotBlank(contentType)) {
                // 允许的图片类型
                final List<String> ALLOW_CONTENT_TYPES = Arrays.asList("image/jpeg", "image/jpg", "image/png", "image/webp");
                ThrowUtils.throwIf(!ALLOW_CONTENT_TYPES.contains(contentType.toLowerCase()),
                        ErrorCode.PARAMS_ERROR, "图片类型错误");
            }
            //5. 校验文件大小
            String contentLengthStr = response.header("Content-Length");
            if (StrUtil.isNotBlank(contentLengthStr)) {
                long contentLength = Long.parseLong(contentLengthStr);
                final long TWO_m = 2 * 1024 * 1024L; //限制上传到文件的大小为2M
                if (contentLength > TWO_m) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "图片大小不能超过2M");
                }
            }
        }finally {
            //关闭资源
            if(response != null){
                response.close();
            }
        }
    }
    /**
     * 获取临时文件
     * @param multipartFile
     * @param uploadPath
     * @return
     * @throws IOException
     */
    public File getFile(MultipartFile multipartFile, String uploadPath) throws IOException {
        // 创建临时文件
        File file = File.createTempFile(uploadPath, null);
        //写入内容
        multipartFile.transferTo(file);
        return file;
    }
    /**
     * 校验文件
     *
     * @param multipartFile multipart 文件
     */
    public void validPicture(MultipartFile multipartFile) {
        ThrowUtils.throwIf(multipartFile == null, ErrorCode.PARAMS_ERROR, "文件不能为空");
        // 1. 校验文件大小
        //文件大小单位是字节
        long fileSize = multipartFile.getSize();
        //1m转为字节
        final long ONE_M = 1024*1024;
        ThrowUtils.throwIf(fileSize > 2 * ONE_M, ErrorCode.PARAMS_ERROR, "文件大小不能超过 2M");
        // 2. 校验文件后缀
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        // 允许上传的文件后缀
        final List<String> ALLOW_FORMAT_LIST = Arrays.asList("jpeg", "jpg", "png", "webp");
        ThrowUtils.throwIf(!ALLOW_FORMAT_LIST.contains(fileSuffix), ErrorCode.PARAMS_ERROR, "文件类型错误");
    }

    /**
     * 删除临时文件
     */
    public void deleteTempFile(File file) {
        if (file == null) {
            return;
        }
        // 删除临时文件
        boolean deleteResult = file.delete();
        if (!deleteResult) {
            log.error("file delete error, filepath = {}", file.getAbsolutePath());
        }
    }

    /**
     * 用流上传文件，不用在服务器中创建临时文件然后再删除，提高了性能
     * @param multipartFile 文件
     * @param bucketName 桶
     * @param key 文件路径
     * @return
     * @throws Exception
     */
    public String uploadToCOS(MultipartFile multipartFile, String bucketName, String key) throws Exception {

        try (InputStream inputStream = multipartFile.getInputStream()) {
            // 元信息配置
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentLength(multipartFile.getSize());
            metadata.setContentType(multipartFile.getContentType());

            // 创建上传请求
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, inputStream, metadata);

            // 上传文件
            cosClient.putObject(putObjectRequest);

            // 生成访问链接
            return "https://" + bucketName + ".cos." + cosClient.getClientConfig().getRegion().getRegionName()
                    + ".myqcloud.com/" + key;
        } finally {
            cosClient.shutdown();
        }
    }
}
